package com.lxhll.personnel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxhll.personnel.dao.RoleDao;
import com.lxhll.personnel.entity.EmployeeRole;
import com.lxhll.personnel.entity.Role;
import com.lxhll.personnel.service.EmployeeRoleService;
import com.lxhll.personnel.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * (Role)表服务实现类
 *
 * @author makejava
 * @since 2021-07-22 14:37:21
 */
@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleDao, Role> implements RoleService {
    @Autowired
    private EmployeeRoleService employeeRoleService;


    /**
     * 一个方法里有多个增删改，加事务
     */

    @Transactional(rollbackFor = Exception.class)
    public  void saveTransfer(Integer rid,Integer[] eids){

        //2.删除用户-角色表中所有旧关系
        employeeRoleService.remove(new QueryWrapper<EmployeeRole>().eq("role_id", rid));


        //3.添加新关系   INSERT INTO sys_user_role ( user_id, role_id ) VALUES ( ?, ? )
        //保存角色
        List<EmployeeRole> list=new ArrayList<>();
        for(Integer eid : eids){
            EmployeeRole ur=new EmployeeRole();
            ur.setEmployeeId(eid);
            ur.setRoleId(rid);
            list.add(ur);
        }

        employeeRoleService.saveBatch(list);   //批量保存用户-角色表的改动
    }


    /**
     * 删除用户和角色
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserAndRole(Integer[] ids){
        //1.删除自身
        this.removeByIds(Arrays.asList(ids));

        //2.删除用户-角色关系  DELETE FROM sys_user_role WHERE (user_id = ?)
        for(Integer id : ids){
            employeeRoleService.remove(new QueryWrapper<EmployeeRole>().eq("role_id", id));
        }
    }


}
